<template>
  <div class="sector">
    <el-table
      :data="userData.gotUsers"
      style="width: 100%"
      :default-sort="{ prop: 'account', order: 'descending' }"
    >
      <el-table-column label="头像" width="100px">
        <template slot-scope="scope">
          <img width="50" v-if="scope.row.avatar" :src="'http://192.168.7.61:4800/images/'+scope.row.avatar" alt />
          <img
            width="50"
            v-else
            src="http://192.168.7.61:4800/images/default.jpg"
            alt
          />
        </template>
      </el-table-column>
      <el-table-column label="账户名" sortable prop="account"></el-table-column>
      <el-table-column label="真名" sortable prop="realName"></el-table-column>
      <el-table-column label="手机号" sortable prop="phone"></el-table-column>

      <el-table-column label="身份" sortable prop="permission">
        <template slot-scope="scope">
          <template v-if="scope.row.role == 1">
            <span style="color: cornflowerblue">求租人</span>
          </template>
          <template v-if="scope.row.role == 2">
            <span style="color: teal">出租人</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="实名认证">
        <template slot-scope="scope">
          <template v-if="scope.row.idVerified == 2">
            <el-button
              type="danger"
              size="mini"
              @click="idVerifyButton(scope.row)"
              >待审核</el-button
            >
          </template>
          <template v-if="scope.row.idVerified == 1">
            <span style="color: teal">已实名</span>
          </template>
          <template v-if="scope.row.idVerified == 0">
            <span style="color: gary">未实名</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column width="600px" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="getOwnerOrdersByUserID(scope.row._id)"
            >出租订单</el-button
          >
          <el-button
            size="mini"
            @click="getCustomerOrdersByUserID(scope.row._id)"
            >求租订单</el-button
          >
          <el-button
            size="mini"
            v-if="scope.row.cars.length > 0"
            @click="getCars(scope.row)"
            >名下车辆</el-button
          >
          <el-button size="mini" @click="handleEdit(scope.row)">修改</el-button>
          <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">Delete</el-button> -->
          <el-popconfirm
            v-if="scope.row.frozen"
            title="确认解冻该用户？"
            @onConfirm="
              changeFronzenStatusByID(scope.row._id, !scope.row.frozen)
            "
          >
            <el-button
              class="delbutton"
              size="mini"
              type="warning"
              slot="reference"
              >解冻</el-button
            >
          </el-popconfirm>
          <el-popconfirm
            v-else
            title="确认冻结该用户？"
            @onConfirm="
              changeFronzenStatusByID(scope.row._id, !scope.row.frozen)
            "
          >
            <el-button
              class="delbutton"
              size="mini"
              type="primary"
              slot="reference"
              >冻结</el-button
            >
          </el-popconfirm>
          <el-popconfirm
            title="确认删除该用户？"
            @onConfirm="deltrigger(scope.row._id)"
          >
            <el-button
              class="delbutton"
              size="mini"
              type="danger"
              slot="reference"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="userData.currentPage"
      :page-sizes="[3, 5, 7, 10]"
      :page-size="userData.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="userData.total"
    ></el-pagination>

    <el-dialog title="实名认证申请" :visible.sync="idVerifyVisible">
      <p>真实姓名： {{ gotCustomerCivilID.realName }}</p>
      <p>身份证号： {{ gotCustomerCivilID.identity }}</p>
      <el-button
        size="mini"
        type="primary"
        @click="idVerifyApprove(gotCustomerCivilID._id)"
        >通过</el-button
      >
      <el-button
        size="mini"
        type="danger"
        @click="idVerifyReject(gotCustomerCivilID._id)"
        >拒绝</el-button
      >
    </el-dialog>

    <el-dialog title="名下所有订单" :visible.sync="cODialogTableVisible">
      <el-table :data="testgotCustomerOrders">
        <el-table-column label="订单号" sortable prop="_id"></el-table-column>
        <el-table-column
          label="车型"
          sortable
          prop="carID.name"
        ></el-table-column>
        <el-table-column
          label="租车天数"
          sortable
          prop="spentTime"
        ></el-table-column>
        <el-table-column
          label="订单金额"
          sortable
          prop="spentMoney"
        ></el-table-column>
        <el-table-column label="状态" sortable prop="status"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="名下所有订单" :visible.sync="oODialogTableVisible">
      <el-table :data="testgotOwnerOrders">
        <el-table-column label="订单号" sortable prop="_id"></el-table-column>
        <el-table-column
          label="求租人"
          sortable
          prop="userID.realName"
        ></el-table-column>
        <el-table-column
          label="车型"
          sortable
          prop="carID.name"
        ></el-table-column>
        <el-table-column
          label="租车天数"
          sortable
          prop="spentTime"
        ></el-table-column>
        <el-table-column
          label="订单金额"
          sortable
          prop="spentMoney"
        ></el-table-column>
        <el-table-column label="状态" sortable prop="status"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="名下所有车辆" :visible.sync="carListVisible">
      <el-table :data="testgotCustomerCars">
        <el-table-column label="型号" sortable prop="model"></el-table-column>
        <el-table-column
          label="车牌号"
          sortable
          prop="licensePlate"
        ></el-table-column>
        <el-table-column
          label="车型"
          sortable
          prop="motorcycleType"
        ></el-table-column>
        <el-table-column label="座位" sortable prop="seat"></el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="修改信息" :visible.sync="changeDialogVisible">
      <el-form :model="changeUserData">
        <el-form-item label="账户名" :label-width="formLabelWidth">
          <el-input
            v-model="changeUserData.account"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth">
          <el-input
            v-model="changeUserData.phone"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input
            type="password"
            v-model="changeUserData.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份" :label-width="formLabelWidth">
          <el-radio-group v-model="changeUserData.role">
            <el-radio border v-model="changeUserData.role" label="2"
              >出租方（车主）</el-radio
            >
            <el-radio border v-model="changeUserData.role" label="1"
              >求租方（穷逼）</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createNamespacedHelpers } from "vuex";
const { mapActions, mapState, mapMutations } = createNamespacedHelpers("user");
const { mapMutations: publicMutations } = createNamespacedHelpers(
  "publicStore"
);
export default {
  created() {
    this.getAllUsers();
    this.setNowBreadcrumb("userlist");
  },
  data() {
    return {
      changeUserData: {
        account: "",
        password: "",
        role: 0,
        avatar: "default.jpg",
        realName: "",
        phone: "",
      },
      gotCustomerOrders: [],
      gotOwnerOrders: [],
      gotCustomerCars: [],
      testgotCustomerOrders: [
        {
          _id: "231231231",
          carID: { name: "2002 honda civic" },
          status: "pending",
        },
        { _id: "231231231", car: "2014 dodge charger", status: "requesting" },
      ],
      testgotOwnerOrders: [
        {
          _id: "231231231",
          userID: { realName: "John" },
          carID: { name: "2002 honda civic" },
          status: "pending",
        },
        { _id: "231231231", car: "2014 dodge charger", status: "requesting" },
      ],
      testgotCustomerCars: [
        {
          model: "2020 honda civic",
          licensePlate: "XA231S",
          motorcycleType: "SUV",
          seat: "5",
        },
      ],
      gotCustomerCivilID: {
        realName: "default",
        identity: "9209419",
      },
      formLabelWidth: "120px",
      cODialogTableVisible: false,
      oODialogTableVisible: false,
      carListVisible: false,
      changeDialogVisible: false,
      idVerifyVisible: false,
      headers: {
        Authorization: "Bearer " + localStorage.token,
      },
      defaultImage: 'this.src="http://localhost:4800/images/default.jpg"',
    };
  },
  computed: {
    ...mapState(["userData"]),
  },
  methods: {
    ...mapActions([
      "getAllUsers",
      "getUserByID",
      "delUserByID",
      "approveID",
      "rejectID",
      "changeFrozenStatus",
      "changeUserInfo",
    ]),
    ...mapMutations([
      "changePageSize",
      "changePageSize",
      "nextPage",
      "changeCurrentPage",
    ]),
    ...publicMutations(["setNowBreadcrumb"]),
    handleEdit(selectedUser) {
      this.changeDialogVisible = true;
      this.changeUserData = selectedUser;
      // console.info(this.changeUserData);
    },
    cancelEdit() {
      this.changeDialogVisible = false;
      this.getAllUsers();
    },
    async confirmEdit() {
      this.changeDialogVisible = false;
      let result = await this.changeUserInfo(this.changeUserData);
      console.info(result);
      if (result.status) {
        this.$notify({
          title: "提示",
          message: "修改成功",
        });
        this.getAllUsers();
      } else {
        this.$notify({
          title: "提示",
          message: "修改失败",
        });
        this.getAllUsers();
      }
    },

    idVerifyButton(data) {
      this.idVerifyVisible = true;
      this.gotCustomerCivilID = data;
    },
    async idVerifyReject(_id) {
      const data = await this.rejectID(_id);
      console.info(data);
    },
    async idVerifyApprove(_id) {
      const data = await this.approveID(_id);
      console.info(data);
    },

    handleSizeChange(val) {
      this.changePageSize(val);
      this.getAllUsers();
    },
    handleCurrentChange(val) {
      this.changeCurrentPage(val);
      this.getAllUsers();
    },
    handleAvatarSuccess(res, file) {
      if (res.status) {
        this.changeUserData.avatar = res.data;
      }
    },
    beforeAvatarUpload(file) {
      const isJPGorPNG =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt20M = file.size / 1024 / 1024 < 20;

      if (!isJPGorPNG) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
      }
      if (!isLt20M) {
        this.$message.error("上传头像图片大小不能超过 20MB!");
      }
      return isJPGorPNG && isLt20M;
    },
    async deltrigger(_id) {
      // console.info("triggered delete " + _id);
      let result = await this.delUserByID(_id);

      if (result.status) {
        this.$notify({
          title: "提示",
          message: "删除成功",
        });
        this.getAllUsers();
      } else {
        this.$notify({
          title: "提示",
          message: "删除失败",
        });
        this.getAllUsers();
      }
      this.getAllUsers();
    },
    async changeFronzenStatusByID(_id, status) {
      const data = await this.changeFrozenStatus({ _id, status });
      console.info(data);
      if (data.status) {
        this.$notify({
          title: "提示",
          message: "操作成功",
        });
        this.getAllUsers();
      } else {
        this.$notify({
          title: "提示",
          message: "操作失败",
        });
        this.getAllUsers();
      }
    },
    getCars(data) {
      this.carListVisible = true;
      this.gotCustomerCars = data.cars;
    },

    async getCustomerOrdersByUserID(_id) {
      this.cODialogTableVisible = true;
      let result = await this.getUserByID(_id);
      this.gotCustomerOrders = result.data.gotUser[0].customerOrders;
    },
    async getOwnerOrdersByUserID(_id) {
      this.oODialogTableVisible = true;
      let result = await this.getUserByID(_id);
      this.gotOwnerOrders = result.data.gotUser[0].ownerOrders;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../assets/scss/public/sector.scss";

.delbutton {
  margin-left: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
